import {chromium, Page} from '@playwright/test';
import {LoginPage} from "../../../electron/operation/GPO_Page_Object/login_page.ts";
import {FirstPage} from "../../../electron/operation/GPO_Page_Object/first_page.ts";
import {ReportListPage} from "../../../electron/operation/GPO_Page_Object/report_list_page.ts";
import * as usageLogger from "../../../electron/operation/usage/usageLogger.ts";
import * as userData from "../../../electron/operation/usage/user-data.ts"
import * as winston from 'winston';
import { Notification } from 'electron';
import * as fs from 'fs';

// 初始化日志库
const logger = winston.createLogger({
    level: 'info',
    format: winston.format.json(),
    transports: [
        new winston.transports.File({ filename: 'log/conDraftReports_error.log', level: 'error' }),
        new winston.transports.File({ filename: 'log/conDraftReports_combined.log' }),
    ],
});

export async function openBrowser(url: string, headless: boolean) {
    console.log('openBrowser called with url:', url, 'headless:', headless); // 添加调试信息
    try{
        // 清空日志文件
        fs.writeFileSync('log/conDraftReports_error.log', '');
        fs.writeFileSync('log/conDraftReports_combined.log', '');
        const browser = await chromium.launch({
            headless: !headless,
            args: ['--start-maximized'],
            executablePath: 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe'
        });
        if (!browser) {
            throw new Error("Playwright browser instance hasn't been initialized yet.");
        }
        const context = await browser.newContext({ viewport: null }); // 创建新的浏览器上下文
        const page = await context.newPage(); // 在上下文中创建新的页面

        const login = new LoginPage(page)
        await login.GPOOpen(url)
        await login.singleSignOn()
        const first = new FirstPage(page)
        first.reportListEntry()
        return {browser, page, context}
    }
    catch (error: any) {
        logger.error(`Error in openBrowser: ${error.stack || error}`);
        throw error; // 重新抛出错误以便调用者可以处理
    }
}

export async function batchConDraftReports(browser: any, page: Page, orderNumbers: string[]) {
    try {
        let report_list_page = new ReportListPage(page)
        await report_list_page.search_order_no_batch(orderNumbers)
        const reportListBodyXpath = `//*[@id="pane-myReportTab"]/div/div/div[2]/div[3]/table/tbody`
        await page.waitForSelector(reportListBodyXpath)
        const trCount = await page.locator(`${reportListBodyXpath}/tr`).count();
        logger.info(`共查询到 ${trCount} 条记录`);
        for (let trNo = 1; trNo <= trCount; trNo++){
            const orderNoXpath = `${reportListBodyXpath}/tr[${trNo}]/td[2]`
            const reportNoXpath = `${reportListBodyXpath}/tr[${trNo}]/td[3]`
            const reportStatusXpath = `${reportListBodyXpath}/tr[${trNo}]/td[5]`
            let orderNoContent = await page.locator(orderNoXpath).textContent()
            let reportNoContent = await page.locator(reportNoXpath).textContent()
            let reportStatusContent = await page.locator(reportStatusXpath).textContent()

            if (reportStatusContent && orderNoContent && reportNoContent) {
                orderNoContent = orderNoContent.replace(/\s+/g, '');
                reportNoContent = reportNoContent.replace(/\s+/g, '');
                reportStatusContent = reportStatusContent.replace(/\s+/g, '');
                logger.info(`Order No: ${orderNoContent} Report No: ${reportNoContent} Report Status: ${reportStatusContent}`);
                
                // 提取 orderNo 的最后两位英文字母
                const orderNoSuffix = orderNoContent.slice(-2);
                if (/^[a-zA-Z]{2}$/.test(orderNoSuffix)) {
                    // 去掉 orderNo 的最后两位英文字母
                    const orderNoWithoutSuffix = orderNoContent.slice(0, -2);

                    // 检查 reportNo 是否符合规则
                    const expectedPattern = new RegExp(`^${orderNoWithoutSuffix}\\d{2}${orderNoSuffix}$`);
                                                        
                    if (expectedPattern.test(reportNoContent) && reportStatusContent === "Approved") {
                        logger.info(`reportNo matches the expected pattern: ${reportNoContent}`);

                        await report_list_page.click_action_button(trNo.toString())

                        const rejectButtonSelector = 'button.el-button.el-button--default.el-button--text span:text("Reject")';
                        const rejectButtons = await page.locator(rejectButtonSelector).all();
                        if (rejectButtons.length > 0) {
                            const lastRejectButton = rejectButtons[rejectButtons.length - 1];
                            await lastRejectButton.click();
                            logger.info(`${orderNoContent} Reject button clicked`);
                        } else {
                            logger.error(`${orderNoContent} No Reject buttons found`);
                        }

                        //
                        const reportRejectDialog = '//div[@aria-label="Report Reject"][@class="el-dialog"]'
                        await page.waitForSelector(reportRejectDialog) // 等待 Reject Dialog 出现
                        // logger.info(`Report Reject Dialog is displayed`)

                        // 选择 Reject Reason Type 下拉框中的 '测试结果错误' 选项
                        const dropdownSelector = '//div[@aria-label="Report Reject"][@class="el-dialog"]/div[2]/div/div/form/div[2]/div/div';
                        await page.locator(dropdownSelector).click(); // 打开下拉框
                        const optionSelector = 'li.el-select-dropdown__item span:has-text("测试结果错误")';
                        await page.locator(optionSelector).click(); // 选择 '测试结果错误'

                        // 点击 Submit 按钮
                        const submitButton = '//div[@aria-label="Report Reject"][@class="el-dialog"]/div[3]/div/button[2]';
                        await page.locator(submitButton).click();

                        // 记录使用情况
                        const data: any[] = [
                            {
                                user_name: `${usageLogger.username}`,
                                user_location: `${usageLogger.location}`,
                                rpa_id: "136",
                                rpa_name: "GPO_BatchReject",
                                rpa_version: "0.0.1",
                                occurrence: `${usageLogger.startTime}`,
                                info: "GPO批量驳回",
                                extra: `${orderNoContent}`
                            }
                        ];
                        console.log('传入API：', data)
                        await userData.sendMonitoringData(data)
                    } else if(!expectedPattern.test(reportNoContent)){
                        logger.info(`reportNo does not match the expected pattern. Expected pattern: ${orderNoWithoutSuffix}\\d{2}${orderNoSuffix}, Original: ${reportNoContent}`);
                    } else if(reportStatusContent !== "Approved"){
                        logger.info(`Report Status is not Approved: ${reportStatusContent}`);
                    }
                }
            }
            }
    }catch (error: any) {
        logger.error(`Web process failed: ${error.stack || error}`);
    }finally {
        if (browser) {
            await browser.close();
        }
        // 任务完成后显示通知
        const notification = new Notification({
            title: 'Task Finished',
            body: '批量reject执行结束，更多详情请查看log日志。',
        });
        notification.show();
    }
}
